package YuanFuDao2;

import java.util.ArrayList;
import java.util.List;

/**
 * 非降序数组，找与target最相近的数的下标
 */
public class Main56 {
    public static void main(String[] args) {
        int[] nums = {1,2,3,3,4,5,6,3,7,8};
        List<Integer> res = new ArrayList<>();
        System.out.println(help(nums, 0, nums.length - 1, 3));
    }

    public static int help(int[] nums,int start,int end,int target){
        int minIndex = (start + end)/2;
        if(start >= end) return start;
        int mid = nums[minIndex];
        int left = nums[(minIndex-1) < start? start:(minIndex-1)];
        int right = nums[(minIndex+1) > end? end:(minIndex+1)];
        int sm = Math.abs(target-mid);
        int sl = Math.abs(target-left);
        int sr = Math.abs(target-right);
        if(sm < sl && sm < sr){
            return minIndex;
        }else{
            int li = help(nums,start,minIndex-1,target);
            int ri = help(nums,minIndex+1,end,target);
            if(Math.abs(target - nums[li]) < Math.abs(target - nums[ri])){
                return li;
            }else if(Math.abs(target - nums[li]) > Math.abs(target - nums[ri])){
                return ri;
            }else{
                return li;
            }
        }

    }
}
